package com.tuxing.draa_data.util.easyExcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.tuxing.draa_data.pojo.DraaTemporaryBook;
import com.tuxing.draa_data.service.draa.DraaBookService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author YuanShiHang
 * @version 1.0
 * @className DraaBookDataListener
 * @description 基础描述: draa图书数据解析监听器
 * @date 2021/11/30 16:51
 */
@Slf4j
public class DraaBookDataListener implements ReadListener<DraaTemporaryBook> {

    //将保存方法当做参数，进行有参构造，新版本的easyExcel不支持spring的bean注入
    private DraaBookService draaBookService;

    public DraaBookService getDraaBookService() {
        return draaBookService;
    }

    public DraaBookDataListener setDraaBookService(DraaBookService draaBookService) {
        this.draaBookService = draaBookService;
        return this;
    }

    public DraaBookDataListener(DraaBookService draaBookService) {
        this.draaBookService = draaBookService;
    }

    /**
     * 每隔1000条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    /**
     * 缓存的数据
     */
    private List<DraaTemporaryBook> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(DraaTemporaryBook draaTemporaryBook, AnalysisContext analysisContext) {

        log.info("解析到一条数据:{}", JSON.toJSON(draaTemporaryBook));
        cachedDataList.add(draaTemporaryBook);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    /**
     * 保存数据，在解析结束后保证剩余不足1000条的数据也能进行保存
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        try {
            draaBookService.saveBatch(cachedDataList);
        } catch (Exception ex) {
            log.error("数据保存失败，失败原因：" + ex.getMessage(), ex);
        }

        log.info("存储数据库成功！");
    }
}
